{{ template "header.html" }}

<div class="item">
    WebToolsGo--生成OTP
</div>
<div class="item">
    <label>
        <textarea name="in">otpauth://totp/WebToolsGo:GetcharZp?secret=2RDVJ2LWY5DIGHDYDY36YCDQD6CB7TYK&issuer=web-tools-go</textarea>
    </label>
</div>
<button onclick="totpGenerate(++index)">生成</button>

<div class="res-item">
    <span>一次性密码：</span>
    <div class="res-div" id="totpAns" style="white-space: pre; background-color:#cccccc;"></div>
</div>
<div class="res-item">
    <span>有效时间(s)：</span>
    <div class="res-div" id="totpExpireTime" style="white-space: pre; background-color:#cccccc;"></div>
</div>

<script>
    // 限制每次只执行最后一次请求
    let index = 0;
    function totpGenerate(subIndex) {
        var url = $("textarea[name='in']").val()
        $.post("/totp", {"url": url}, function (res) {
            $("#totpAns").text(res.data.code)
            $("#totpExpireTime").text(res.data.expiredTime)

            var timer = setInterval(function () {
                if (subIndex !== index) {
                    clearInterval(timer)
                    return
                }
                if (res.data.expiredTime > 0) {
                    res.data.expiredTime--
                    $("#totpExpireTime").text(res.data.expiredTime)
                } else {
                    clearInterval(timer)
                    totpGenerate(subIndex)
                }
            }, 1000)
        }, "json")
    }
</script>

{{ template "footer.html" }}